package com.yin.waimai.service.impl;

import com.yin.waimai.dto.AddressDTO;             
import com.yin.waimai.dto.CreateOrderRequestDTO; 
import com.yin.waimai.dto.DeliveryPersonDTO;     
import com.yin.waimai.dto.OrderDTO;
import com.yin.waimai.dto.OrderNotificationDTO;
import com.yin.waimai.enums.OrderStatus;
import com.yin.waimai.enums.LogisticsStatus;
import com.yin.waimai.model.Address;              
import com.yin.waimai.model.LogisticsTrace;
import com.yin.waimai.model.Order;
import com.yin.waimai.repository.LogisticsTraceRepository;
import com.yin.waimai.repository.OrderRepository;
import com.yin.waimai.service.AmapWebService;
import com.yin.waimai.service.NotificationService;
import com.yin.waimai.service.OrderService;
import com.yin.waimai.service.WebSocketService;
import com.yin.waimai.service.impl.AmapWebServiceImpl.RouteInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

import com.yin.waimai.enums.DeliveryPersonStatus;
import com.yin.waimai.service.DeliveryPersonService;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.geo.Point;

@Service
public class OrderServiceImpl implements OrderService {
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
    
    // 定义常量
    private static final BigDecimal FIRST_WEIGHT_FEE = new BigDecimal("10.00");
    private static final double FIRST_WEIGHT_KG = 1.0;
    private static final BigDecimal ADDITIONAL_WEIGHT_FEE_PER_KG = new BigDecimal("2.00");
    private static final double FREE_DISTANCE_KM_THRESHOLD = 3.0;
    private static final BigDecimal DISTANCE_FEE_PER_KM = new BigDecimal("1.50");
    
    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private LogisticsTraceRepository logisticsTraceRepository;
    
    @Autowired
    private AmapWebService amapWebService;
    
    @Autowired
    private DeliveryPersonService deliveryPersonService;
    
    @Autowired
    private WebSocketService webSocketService;
    
    @Autowired
    private NotificationService notificationService;
    
    @Override
    @Transactional
    public OrderDTO createOrder(CreateOrderRequestDTO requestDTO, String username) {
        log.info("Service: Attempting to create order from DTO: {}", requestDTO);
        Order order = convertCreateDtoToOrder(requestDTO);
    
        order.setOrderNumber("ORD" + UUID.randomUUID().toString().substring(0, 12).toUpperCase());
        order.setStatus(OrderStatus.PENDING_COLLECTION);
        order.setCreationTime(LocalDateTime.now());
        order.setCreatorUsername(username); // 设置创建者用户名
    
        Integer distanceMeters = null;
        if (order.getShipperInfo() != null && order.getRecipientInfo() != null) {
            Optional<RouteInfo> routeInfoOpt = amapWebService.getOrderRoutePath(order.getShipperInfo(), order.getRecipientInfo());
            if (routeInfoOpt.isPresent() && routeInfoOpt.get().isValid()) {
                distanceMeters = routeInfoOpt.get().getDistanceMeters();
                log.info("Order {} - Calculated distance: {} meters for fee calculation.", order.getOrderNumber(), distanceMeters);
            } else {
                log.warn("Order {} - Could not retrieve valid distance for fee calculation. Using weight-based fee only.", order.getOrderNumber());
            }
        } else {
            log.warn("Order {} - Shipper or Recipient info is null. Using weight-based fee only.", order.getOrderNumber());
        }
        order.setCalculatedFee(calculateFee(order.getWeight(), distanceMeters));
    
        Order savedOrder = orderRepository.save(order);
        log.info("Order created successfully: {}, Fee: {}", savedOrder.getOrderNumber(), savedOrder.getCalculatedFee());
        addInitialLogisticsTrace(savedOrder);
    
        OrderDTO orderDTO = convertOrderToDto(savedOrder);
        
        // 发送订单创建邮件通知（如果提供了邮箱且启用了通知）
        sendOrderCreatedNotification(savedOrder, requestDTO);
        
        // 广播新订单给所有配送员
        webSocketService.broadcastNewOrder(orderDTO);
        
        return orderDTO;
    }
    
    @Override
    @Transactional
    public OrderDTO acceptOrder(String orderNumber, String deliveryPersonId, String operator) {
        log.info("Delivery person {} accepting order {}", deliveryPersonId, orderNumber);
        
        // 查找订单
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
        if (orderOpt.isEmpty()) {
            log.error("Order not found with number: {}", orderNumber);
            throw new RuntimeException("Order not found: " + orderNumber);
        }
        Order order = orderOpt.get();
        
        // 检查订单状态是否允许接单
        if (order.getStatus() != OrderStatus.PENDING_COLLECTION) {
            log.warn("Cannot accept order {} with status {}", orderNumber, order.getStatus());
            throw new IllegalArgumentException("Cannot accept order with status: " + order.getStatus());
        }
        
        // 检查订单是否已被分配
        if (order.getDeliveryPersonId() != null) {
            log.warn("Order {} already assigned to delivery person {}", orderNumber, order.getDeliveryPersonId());
            throw new IllegalArgumentException("Order already assigned to another delivery person");
        }
        
        // 查找配送员
        Optional<DeliveryPersonDTO> deliveryPersonOpt = deliveryPersonService.findById(deliveryPersonId);
        if (deliveryPersonOpt.isEmpty()) {
            log.error("Delivery person not found with ID: {}", deliveryPersonId);
            throw new RuntimeException("Delivery person not found: " + deliveryPersonId);
        }
        
        // 更新订单的配送员ID
        order.setDeliveryPersonId(deliveryPersonId);
        
        // 保存订单
        Order updatedOrder = orderRepository.save(order);
        log.info("Order {} accepted by delivery person {}", orderNumber, deliveryPersonId);
        
        // 更新配送员状态为配送中
        deliveryPersonService.updateStatus(deliveryPersonId, DeliveryPersonStatus.DELIVERING);
        
        // 添加物流轨迹
        String description = "订单已被配送员接单: " + deliveryPersonOpt.get().getName();
        String location = order.getShipperInfo() != null ? order.getShipperInfo().getCity() : "未知地点";
        
        LogisticsTrace trace = new LogisticsTrace();
        trace.setOrderId(updatedOrder.getId());
        trace.setOrderNumber(updatedOrder.getOrderNumber());
        trace.setTimestamp(LocalDateTime.now());
        trace.setStatus(LogisticsStatus.PENDING_COLLECTION);
        trace.setDescription(description);
        trace.setLocation(location);
        trace.setOperator(operator);
        logisticsTraceRepository.save(trace);
        log.info("Logistics trace added for order {}: {}", orderNumber, description);
        
        // 通知订单已被接单
        OrderDTO orderDTO = convertOrderToDto(updatedOrder);  
        // 替换为：
        webSocketService.notifyOrderAccepted(orderDTO, deliveryPersonOpt.get().getName());
        
        return orderDTO;
    }
    
    @Override
    public OrderDTO getOrderByOrderNumber(String orderNumber) { // <--- 修改：返回DTO
        log.debug("Service: Getting order DTO by number: {}", orderNumber);
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
        return orderOpt.map(this::convertOrderToDto).orElse(null);
    }
    
    @Override
    public Optional<Order> findOrderEntityByNumber(String orderNumber) { // <--- 方法名调整
        log.debug("Service: Finding order entity by number: {}", orderNumber);
        return orderRepository.findByOrderNumber(orderNumber);
    }
    
    // findOrderById 如果Controller不直接用，可以考虑移除
    // @Override
    // public Optional<Order> findOrderById(String id) {
    //     log.debug("Finding order by ID: {}", id);
    //     return orderRepository.findById(id);
    // }
    
    @Override
    @Transactional
    public OrderDTO updateOrderStatusAndAddTrace(String orderNumber, OrderStatus newOrderStatus, String operator, String location, String description) { // <--- 修改：返回DTO
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
        if (orderOpt.isEmpty()) {
            log.error("Order not found with number: {}", orderNumber);
            throw new RuntimeException("Order not found: " + orderNumber); // 或者自定义异常
        }
        Order order = orderOpt.get();
    
        if (!isStatusTransitionValid(order.getStatus(), newOrderStatus)) {
            log.warn("Invalid status transition from {} to {} for order {}", order.getStatus(), newOrderStatus, orderNumber);
            throw new IllegalArgumentException("Invalid status transition from " + order.getStatus() + " to " + newOrderStatus);
        }
    
        order.setStatus(newOrderStatus);
        LocalDateTime now = LocalDateTime.now();
        // 你已有的时间更新逻辑
        if (newOrderStatus == OrderStatus.COLLECTED && order.getPickupTime() == null) {
            order.setPickupTime(now);
        } else if (newOrderStatus == OrderStatus.SIGNED || newOrderStatus == OrderStatus.COMPLETED) {
            if (order.getDeliveryTime() == null) {
                order.setDeliveryTime(now);
            }
        }
    
    
        Order updatedOrder = orderRepository.save(order);
        log.info("Order {} status updated to {}. Operator: {}, Location: {}", orderNumber, newOrderStatus, operator, location);
    
        Optional<LogisticsStatus> logisticsStatusOpt = mapOrderStatusToLogisticsStatus(newOrderStatus, description);
        if (logisticsStatusOpt.isPresent()) {
            LogisticsTrace trace = new LogisticsTrace();
            trace.setOrderId(updatedOrder.getId()); // 使用 orderId
            trace.setOrderNumber(updatedOrder.getOrderNumber());
            trace.setTimestamp(now);
            trace.setStatus(logisticsStatusOpt.get());
            trace.setDescription(description);
            trace.setLocation(location);
            trace.setOperator(operator);
            logisticsTraceRepository.save(trace);
            log.info("Logistics trace added for order {}: LogisticsStatus {}", orderNumber, logisticsStatusOpt.get());
        } else {
            log.info("No direct logistics trace generated for OrderStatus {} for order {}", newOrderStatus, orderNumber);
        }
        
        // 发送订单状态更新邮件通知
        sendOrderStatusUpdateNotification(updatedOrder, newOrderStatus, location, operator, description);
        
        return convertOrderToDto(updatedOrder); // <--- Entity to DTO转换后返回
    }
    
    @Override
    public List<LogisticsTrace> getLogisticsTracesByOrderNumber(String orderNumber) {
        // Controller 中 getOrderTraces 会先调用 findOrderEntityByNumber 判断订单是否存在
        // 所以这里可以假设订单存在，或者再次查询并判断
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber); // 或者用 findOrderEntityByNumber
        if (orderOpt.isPresent()) {
            // 确保按时间升序或降序返回，根据前端需求
            return logisticsTraceRepository.findByOrderIdOrderByTimestampAsc(orderOpt.get().getId());
        }
        log.warn("No order found with number {} to get traces.", orderNumber);
        return Collections.emptyList();
    }
    
    @Override
    public List<List<Double>> getOrderRouteCoordinates(String orderNumber) {
        // Controller 中 getOrderPath 会先调用 findOrderEntityByNumber 判断订单是否存在
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber); // 或者用 findOrderEntityByNumber
        if (orderOpt.isPresent()) {
            Order order = orderOpt.get();
            if (order.getShipperInfo() != null && order.getRecipientInfo() != null) {
                Optional<RouteInfo> routeInfoOpt = amapWebService.getOrderRoutePath(order.getShipperInfo(), order.getRecipientInfo());
                if (routeInfoOpt.isPresent() && routeInfoOpt.get().hasValidPath()) {
                    return routeInfoOpt.get().getPathCoordinates();
                } else {
                    log.warn("No valid path coordinates found in RouteInfo for order {}", orderNumber);
                }
            } else {
                log.warn("Order {} is missing shipper or recipient info for route coordinates.", orderNumber);
            }
        } else {
            log.warn("Order {} not found for route coordinates.", orderNumber);
        }
        return Collections.emptyList(); // 保持返回空列表
    }
    
    // --- DTO 与 Model 转换辅助方法 ---
    private Order convertCreateDtoToOrder(CreateOrderRequestDTO dto) {
        if (dto == null) return null;
        Order order = new Order();
        // BeanUtils.copyProperties(dto, order); // 简单复制，但地址需要特殊处理
        order.setShipperInfo(convertAddressDtoToAddress(dto.getShipperInfo()));
        order.setRecipientInfo(convertAddressDtoToAddress(dto.getRecipientInfo()));
        order.setItemDescription(dto.getItemDescription());
        order.setWeight(dto.getWeight());
        // 其他 order 特有的属性，如 userId 等，需要从 Principal 或其他地方设置
        return order;
    }
    
    private OrderDTO convertOrderToDto(Order order) {
        if (order == null) return null;
        OrderDTO dto = new OrderDTO();
        BeanUtils.copyProperties(order, dto, "shipperInfo", "recipientInfo"); // 复制大部分属性，排除地址
        dto.setShipperInfo(convertAddressToAddressDto(order.getShipperInfo()));
        dto.setRecipientInfo(convertAddressToAddressDto(order.getRecipientInfo()));
        // 手动设置 OrderDTO 特有的或需要特殊转换的属性
        // dto.setSomeOtherField(...);
        return dto;
    }
    
    private Address convertAddressDtoToAddress(AddressDTO dto) {
        if (dto == null) return null;
        Address address = new Address();
        BeanUtils.copyProperties(dto, address);
        return address;
    }
    
    private AddressDTO convertAddressToAddressDto(Address address) {
        if (address == null) return null;
        AddressDTO dto = new AddressDTO();
        BeanUtils.copyProperties(address, dto);
        return dto;
    }

    private BigDecimal calculateFee(Double weightKg, Integer distanceMeters) {
        if (weightKg == null || weightKg <= 0) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
    
        BigDecimal weightBasedFee = FIRST_WEIGHT_FEE;
        if (weightKg > FIRST_WEIGHT_KG) {
            double additionalWeight = weightKg - FIRST_WEIGHT_KG;
            weightBasedFee = weightBasedFee.add(
                    ADDITIONAL_WEIGHT_FEE_PER_KG.multiply(BigDecimal.valueOf(additionalWeight))
            );
        }
    
        BigDecimal distanceBasedFeeComponent = BigDecimal.ZERO;
        if (distanceMeters != null && distanceMeters > 0) {
            double distanceKm = distanceMeters / 1000.0;
            log.info("Calculating distance fee component for {} km", String.format("%.2f", distanceKm));
            if (distanceKm > FREE_DISTANCE_KM_THRESHOLD) {
                double chargeableDistanceKm = distanceKm - FREE_DISTANCE_KM_THRESHOLD;
                distanceBasedFeeComponent = DISTANCE_FEE_PER_KM.multiply(BigDecimal.valueOf(chargeableDistanceKm));
            }
        } else {
            log.info("No valid distance provided ({} meters), distance fee component is zero.", distanceMeters);
        }
    
        BigDecimal totalFee = weightBasedFee.add(distanceBasedFeeComponent);
        log.info("Calculated Fee Details: WeightPart={}, DistancePart={}, Total={}",
                weightBasedFee.setScale(2, RoundingMode.HALF_UP),
                distanceBasedFeeComponent.setScale(2, RoundingMode.HALF_UP),
                totalFee.setScale(2, RoundingMode.HALF_UP));
    
        return totalFee.setScale(2, RoundingMode.HALF_UP);
    }
    
    private void addInitialLogisticsTrace(Order order) {
        // ... (你的初始轨迹逻辑保持不变) ...
        LogisticsTrace initialTrace = new LogisticsTrace();
        initialTrace.setOrderId(order.getId());
        initialTrace.setOrderNumber(order.getOrderNumber());
        initialTrace.setTimestamp(order.getCreationTime());
        Optional<LogisticsStatus> initialLogisticsStatusOpt = mapOrderStatusToLogisticsStatus(OrderStatus.PENDING_COLLECTION, OrderStatus.PENDING_COLLECTION.getDescription());
        if (initialLogisticsStatusOpt.isPresent()){
            initialTrace.setStatus(initialLogisticsStatusOpt.get());
        } else {
            log.error("Failed to map initial OrderStatus.PENDING_COLLECTION to LogisticsStatus for order {}", order.getOrderNumber());
            // 可以设置一个默认的 LogisticsStatus 或者抛出异常，取决于业务需求无法解析符号 'UNKNOWN'
            initialTrace.setStatus(LogisticsStatus.UNKNOWN); // 示例默认值
        }
        initialTrace.setDescription(OrderStatus.PENDING_COLLECTION.getDescription());
        initialTrace.setLocation(order.getShipperInfo() != null ? order.getShipperInfo().getCity() : "未知发货地");
        initialTrace.setOperator("系统");
        logisticsTraceRepository.save(initialTrace);
        log.info("Initial logistics trace added for order: {}", order.getOrderNumber());
    }
    
    /**
     * 发送订单创建邮件通知
     * @param order 订单对象
     * @param requestDTO 创建订单请求DTO
     */
    private void sendOrderCreatedNotification(Order order, CreateOrderRequestDTO requestDTO) {
        try {
            // 检查是否有收件人邮箱且启用了邮件通知
            String recipientEmail = null;
            boolean emailNotificationEnabled = false;
            
            if (requestDTO.getRecipientInfo() != null) {
                recipientEmail = requestDTO.getRecipientInfo().getEmail();
                emailNotificationEnabled = requestDTO.getRecipientInfo().isEmailNotificationEnabled();
            }
            
            if (StringUtils.hasText(recipientEmail) && emailNotificationEnabled && 
                notificationService.isValidEmail(recipientEmail)) {
                
                OrderNotificationDTO notification = new OrderNotificationDTO();
                notification.setOrderNumber(order.getOrderNumber());
                notification.setRecipientEmail(recipientEmail);
                notification.setOrderStatus(order.getStatus().name());
                notification.setNotificationType("ORDER_CREATED");
                notification.setEmailNotificationEnabled(true);
                notification.setCalculatedFee(order.getCalculatedFee());
                
                // 设置收发件人信息
                if (order.getRecipientInfo() != null) {
                    notification.setRecipientName(order.getRecipientInfo().getName());
                }
                if (order.getShipperInfo() != null) {
                    notification.setShipperName(order.getShipperInfo().getName());
                }
                
                // 发送异步邮件通知
                notificationService.sendAsyncEmailNotification(notification);
                log.info("订单创建邮件通知已发送: 订单号={}, 收件人={}", 
                        order.getOrderNumber(), recipientEmail);
            }
        } catch (Exception e) {
            log.error("发送订单创建邮件通知失败: 订单号={}, 错误信息={}", 
                    order.getOrderNumber(), e.getMessage(), e);
        }
    }
    
    /**
     * 发送订单状态更新邮件通知
     * @param order 订单对象
     * @param newStatus 新状态
     * @param location 位置
     * @param operator 操作员
     * @param description 描述
     */
    private void sendOrderStatusUpdateNotification(Order order, OrderStatus newStatus, 
                                                   String location, String operator, String description) {
        try {
            // 检查是否有收件人邮箱（这里假设邮箱信息存储在Address中）
            String recipientEmail = null;
            boolean emailNotificationEnabled = false;
            
            if (order.getRecipientInfo() != null) {
                recipientEmail = order.getRecipientInfo().getEmail();
                emailNotificationEnabled = order.getRecipientInfo().isEmailNotificationEnabled();
            }
            
            if (StringUtils.hasText(recipientEmail) && emailNotificationEnabled && 
                notificationService.isValidEmail(recipientEmail)) {
                
                OrderNotificationDTO notification = new OrderNotificationDTO();
                notification.setOrderNumber(order.getOrderNumber());
                notification.setRecipientEmail(recipientEmail);
                notification.setOrderStatus(newStatus.name());
                notification.setNotificationType("ORDER_STATUS_UPDATED");
                notification.setEmailNotificationEnabled(true);
                notification.setLocation(location);
                notification.setOperator(operator);
                notification.setDescription(description);
                
                // 设置收发件人信息
                if (order.getRecipientInfo() != null) {
                    notification.setRecipientName(order.getRecipientInfo().getName());
                }
                if (order.getShipperInfo() != null) {
                    notification.setShipperName(order.getShipperInfo().getName());
                }
                
                // 发送异步邮件通知
                notificationService.sendAsyncEmailNotification(notification);
                log.info("订单状态更新邮件通知已发送: 订单号={}, 状态={}, 收件人={}", 
                        order.getOrderNumber(), newStatus, recipientEmail);
            }
        } catch (Exception e) {
            log.error("发送订单状态更新邮件通知失败: 订单号={}, 状态={}, 错误信息={}", 
                    order.getOrderNumber(), newStatus, e.getMessage(), e);
        }
    }
    
    private Optional<LogisticsStatus> mapOrderStatusToLogisticsStatus(OrderStatus orderStatus, String description) {
        // ... (你的状态映射逻辑保持不变) ...
        switch (orderStatus) {
            case PENDING_COLLECTION: return Optional.of(LogisticsStatus.PENDING_COLLECTION);
            case COLLECTED: return Optional.of(LogisticsStatus.COLLECTED);
            case TRANSPORTING:
                if (description != null && (description.contains("入库") || description.contains("分拣中心"))) {
                    return Optional.of(LogisticsStatus.WAREHOUSED);
                }
                return Optional.of(LogisticsStatus.TRANSPORTING);
            case OUT_FOR_DELIVERY: return Optional.of(LogisticsStatus.OUT_FOR_DELIVERY);
            case DELIVERY_FAILED: return Optional.of(LogisticsStatus.DELIVERY_FAILED);
            case SIGNED: return Optional.of(LogisticsStatus.SIGNED);
            case CANCELLED: return Optional.of(LogisticsStatus.CANCELLED);
            case PENDING_PAYMENT: // 支付状态通常不直接生成物流轨迹，除非有特殊业务
            case COMPLETED:       // 完成状态通常由SIGNED触发，除非有额外流程
            case REFUNDED:        // 退款状态的物流可能是逆向的，这里不直接映射
            default:
                log.debug("OrderStatus {} with description '{}' does not have a direct mapping to LogisticsStatus for standard trace.", orderStatus, description);
                return Optional.empty();
        }
    }
    
    private boolean isStatusTransitionValid(OrderStatus currentStatus, OrderStatus newStatus) {
        // ... (你的状态转换校验逻辑保持不变) ...
        if (newStatus == OrderStatus.CANCELLED) {
            // 允许从待揽收或待支付取消
            return currentStatus == OrderStatus.PENDING_PAYMENT || currentStatus == OrderStatus.PENDING_COLLECTION;
        }
        if (newStatus == OrderStatus.REFUNDED) {
            // 通常从已完成或特定退货流程后才能退款
            return currentStatus == OrderStatus.COMPLETED || currentStatus == OrderStatus.SIGNED; // 假设签收后才能申请退款并完成
        }
        // 已终态的订单不能再变
        if (currentStatus == OrderStatus.COMPLETED || currentStatus == OrderStatus.CANCELLED || currentStatus == OrderStatus.REFUNDED) {
            return false;
        }
        switch (currentStatus) {
            case PENDING_PAYMENT:
                return newStatus == OrderStatus.PENDING_COLLECTION; // 支付后变为待揽收
            case PENDING_COLLECTION:
                return newStatus == OrderStatus.COLLECTED;
            case COLLECTED:
                return newStatus == OrderStatus.TRANSPORTING;
            case TRANSPORTING:
                return newStatus == OrderStatus.OUT_FOR_DELIVERY;
            case OUT_FOR_DELIVERY:
                return newStatus == OrderStatus.SIGNED || newStatus == OrderStatus.DELIVERY_FAILED;
            case DELIVERY_FAILED:
                return newStatus == OrderStatus.OUT_FOR_DELIVERY; // 允许重新派送
            case SIGNED:
                return newStatus == OrderStatus.COMPLETED; // 签收后可以标记为完成
            default:
                return false;
        }
    }
        
        @Override
        @Transactional
        public OrderDTO assignDeliveryPerson(String orderNumber, String deliveryPersonId, String operator) {
            log.info("Assigning delivery person {} to order {}", deliveryPersonId, orderNumber);
            
            // 查找订单
            Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
            if (orderOpt.isEmpty()) {
                log.error("Order not found with number: {}", orderNumber);
                throw new RuntimeException("Order not found: " + orderNumber);
            }
            Order order = orderOpt.get();
            
            // 检查订单状态是否允许分配配送员
            if (order.getStatus() != OrderStatus.PENDING_COLLECTION && 
                order.getStatus() != OrderStatus.COLLECTED) {
                log.warn("Cannot assign delivery person to order {} with status {}", orderNumber, order.getStatus());
                throw new IllegalArgumentException("Cannot assign delivery person to order with status: " + order.getStatus());
            }
            
            // 移除对发货地址坐标的检查
            // if (order.getShipperInfo() == null || 
            //     order.getShipperInfo().getLongitude() == null || 
            //     order.getShipperInfo().getLatitude() == null) {
            //     log.warn("Order {} has no valid shipper location for auto-assignment", orderNumber);
            //     throw new IllegalArgumentException("Order has no valid shipper location for auto-assignment");
            // }
            
            // 查找配送员
            Optional<DeliveryPersonDTO> deliveryPersonOpt = deliveryPersonService.findById(deliveryPersonId);
            if (deliveryPersonOpt.isEmpty()) {
                log.error("Delivery person not found with ID: {}", deliveryPersonId);
                throw new RuntimeException("Delivery person not found: " + deliveryPersonId);
            }
            
            // 更新订单的配送员ID
            order.setDeliveryPersonId(deliveryPersonId);
            
            // 保存订单
            Order updatedOrder = orderRepository.save(order);
            log.info("Order {} assigned to delivery person {}", orderNumber, deliveryPersonId);
            
            // 添加物流轨迹
            String description = "订单已分配给配送员: " + deliveryPersonOpt.get().getName();
            String location = order.getShipperInfo() != null ? order.getShipperInfo().getCity() : "未知地点";
            
            LogisticsTrace trace = new LogisticsTrace();
            trace.setOrderId(updatedOrder.getId());
            trace.setOrderNumber(updatedOrder.getOrderNumber());
            trace.setTimestamp(LocalDateTime.now());
            trace.setStatus(LogisticsStatus.PENDING_COLLECTION);
            trace.setDescription(description);
            trace.setLocation(location);
            trace.setOperator(operator);
            logisticsTraceRepository.save(trace);
            log.info("Logistics trace added for order {}: {}", orderNumber, description);
            
            // 通知订单已被分配
            OrderDTO orderDTO = convertOrderToDto(updatedOrder);
            webSocketService.notifyOrderAssigned(orderDTO, deliveryPersonOpt.get().getName());
            
            return orderDTO;
        }
        @Override
        @Transactional
        public OrderDTO autoAssignDeliveryPerson(String orderNumber, String operator) {
            log.info("Auto-assigning delivery person to order {}", orderNumber);
            
            // 查找订单
            Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
            if (orderOpt.isEmpty()) {
                log.error("Order not found with number: {}", orderNumber);
                throw new RuntimeException("Order not found: " + orderNumber);
            }
            Order order = orderOpt.get();
            
            // 检查订单状态是否允许分配配送员
            if (order.getStatus() != OrderStatus.PENDING_COLLECTION && 
                order.getStatus() != OrderStatus.COLLECTED) {
                log.warn("Cannot assign delivery person to order {} with status {}", orderNumber, order.getStatus());
                throw new IllegalArgumentException("Cannot assign delivery person to order with status: " + order.getStatus());
            }
            
            // 获取发货地址的坐标
            if (order.getShipperInfo() == null || 
                order.getShipperInfo().getLongitude() == null || 
                order.getShipperInfo().getLatitude() == null) {
                log.warn("Order {} has no valid shipper location for auto-assignment", orderNumber);
                throw new IllegalArgumentException("Order has no valid shipper location for auto-assignment");
            }
            
            // 创建发货地点
            Point shipperLocation = new Point(
                order.getShipperInfo().getLongitude(), 
                order.getShipperInfo().getLatitude()
            );
            
            // 设置查找范围（默认5公里）
            Distance distance = new Distance(5, Metrics.KILOMETERS);
            
            // 查找附近的空闲配送员
            List<DeliveryPersonDTO> nearbyIdleDeliveryPersons = deliveryPersonService.findNearbyIdle(shipperLocation, distance);
            
            if (nearbyIdleDeliveryPersons.isEmpty()) {
                log.warn("No idle delivery persons found near order {}", orderNumber);
                return convertOrderToDto(order); // 返回未分配的订单
            }
            
            // 选择最近的配送员（这里简单地选择列表中的第一个）
            DeliveryPersonDTO selectedDeliveryPerson = nearbyIdleDeliveryPersons.get(0);
            
            // 调用分配方法
            return assignDeliveryPerson(orderNumber, selectedDeliveryPerson.getId(), operator);
        }
        
        @Override
        public List<OrderDTO> getOrdersByDeliveryPersonId(String deliveryPersonId) {
            log.info("Finding orders for delivery person: {}", deliveryPersonId);
            List<Order> orders = orderRepository.findByDeliveryPersonId(deliveryPersonId);
            return orders.stream()
                    .map(this::convertOrderToDto)
                    .collect(Collectors.toList());
        }
    
    @Override
    public List<OrderDTO> getAvailableOrders() {
        log.info("Getting available orders for delivery persons");
        List<Order> orders = orderRepository.findByStatusAndDeliveryPersonIdIsNull(OrderStatus.PENDING_COLLECTION);
        return orders.stream()
                .map(this::convertOrderToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public long deleteByOrderNumber(String orderNumber) {
        log.info("Deleting order with order number: {}", orderNumber);
        return orderRepository.deleteByOrderNumber(orderNumber);
    }
    
    @Override
    public List<OrderDTO> getRecentOrders(int limit) {
        log.info("Getting {} most recent orders", limit);
        List<Order> orders = orderRepository.findTop10ByOrderByCreationTimeDesc();
        if (limit > 0 && limit < orders.size()) {
            orders = orders.subList(0, limit);
        }
        return orders.stream()
                .map(this::convertOrderToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<OrderDTO> findAllOrders() {
        log.info("Finding all orders");
        return orderRepository.findAll().stream()
                .map(this::convertOrderToDto)
                .collect(Collectors.toList());
    }
    
    @Override
    public long countOrders() {
        log.info("Counting all orders");
        return orderRepository.count();
    }
    
    @Override
    public long countCompletedOrders() {
        log.info("Counting completed orders");
        return orderRepository.countByStatus(OrderStatus.COMPLETED);
    }
}